#!/usr/bin/env python3
# Copyright (c) 2019-2020 Windy Albert

import hashlib
import ecdsa
import base58check

from keyTree import *
import bech32


class addrBNB(object):
    def __init__(self, obj):
        self.obj = obj
        
    def getWallet(self,path):
        xprv = keyTree().getChildpriKey(self.obj,path)
        xprv_hex = base58check.b58decode(xprv["xprv"])
        prikey_hex = xprv_hex[46:78].hex()
        data = "80"+prikey_hex + "01" #compressed
        sha256_1 = hashlib.new('sha256',bytes.fromhex(data))
        sha256_2 = hashlib.new('sha256',bytes.fromhex(sha256_1.hexdigest()))
        wif_b58 = base58check.b58encode(bytes.fromhex(data+(sha256_2.hexdigest())[0:8]))

        path = self.obj["path"] + "/" + path
        wif = str(wif_b58,'utf-8')
        pubkey = self.getPubkey(wif)
        addr = self.getAddr(pubkey)
                
        return {"path":path,"wif":wif,"addr":addr}
    
    def getAddr(self,pubkey):
        pubkeyID = self.__getPubkeyID(pubkey)
        data = bech32.convertbits(bytes.fromhex(pubkeyID),8,5) # data.insert(0,0) # diffrence from BTC
        addr = bech32.bech32_encode("bnb",data)
        return addr

    def __getPubkeyID(self,pubkey):
        sha256  = hashlib.new('sha256',bytes.fromhex(pubkey))
        hash160 = hashlib.new('ripemd160',bytes.fromhex(sha256.hexdigest()))
        return (hash160.hexdigest())

    def getPubkey(self,wif):
        wif_hex = base58check.b58decode(wif)
        prikey = wif_hex[1:33]
        sk = ecdsa.SigningKey.from_string( bytes.fromhex(prikey.hex()), curve=ecdsa.SECP256k1)    
        vk = sk.get_verifying_key() #this is your verification key (public key)
        public_key = vk.to_string("compressed").hex()
        return public_key

def main():
    print("This is demo ...")
    
if __name__ == '__main__':
    main()